package com.newki.profile.mvi.vm

import androidx.lifecycle.SavedStateHandle
import com.android.basiclib.base.mvi.BaseEISViewModel
import com.android.basiclib.bean.OkResult
import com.newki.profile.mvi.eis.ArticleUiState
import com.newki.profile.mvi.eis.BannerUiState
import com.newki.profile.mvi.eis.ProfileEffect
import com.newki.profile.mvi.eis.ProfileIntent
import com.newki.profile.mvi.eis.ProfileState
import com.newki.profile_api.repository.ArticleUserCase
import com.newki.profile_api.repository.ProfileRepository
import dagger.hilt.android.lifecycle.HiltViewModel

import javax.inject.Inject


@HiltViewModel
class ProfileViewModel @Inject constructor(
    private val repository: ProfileRepository,
    val savedState: SavedStateHandle
) : BaseEISViewModel<ProfileEffect, ProfileIntent, ProfileState>() {

    @Inject
    lateinit var articleUserCase: ArticleUserCase

    override fun initUiState(): ProfileState = ProfileState(BannerUiState.INIT, ArticleUiState.INIT)

    override fun handleIntent(intent: ProfileIntent) {
        when (intent) {
            ProfileIntent.FetchBanner -> fetchBanner()
            ProfileIntent.FetchArticle -> fetchArticle()
        }
    }

    //测试加载 WanAndroid - Banner 的数据
    private fun fetchBanner() {

        launchOnUI {

            //开始Loading
            loadStartProgress()

            val bannerResult = repository.fetchBanner()

            if (bannerResult is OkResult.Success) {
                //成功
                loadHideProgress()

                updateUiState {
                    copy(bannerUiState = BannerUiState.SUCCESS(bannerResult.data))
                }

            } else {
                val message = (bannerResult as OkResult.Error).exception.message
                sendEffect(ProfileEffect.ToastArticle(message))
            }

        }

    }

    //加载页面数据，这里使用测试接口 WanAndroid - Article 的数据
    private fun fetchArticle() {

        launchOnUI {

            loadStartLoading()

            val articleResult = articleUserCase.invoke()

            if (articleResult is OkResult.Success) {
                //成功
                loadSuccess()

                updateUiState {
                    copy(articleUiState = ArticleUiState.SUCCESS(articleResult.data))
                }

            } else {
                val message = (articleResult as OkResult.Error).exception.message
                sendEffect(ProfileEffect.ToastArticle(message))
            }

        }

    }

}